<template>
  <view class="page">
    <!-- <button @click="handleTest">测试</button> -->
    <view class="page-hd flex">
      <view class="logo">
        <image class="logo-img" src="/static/logo.png" mode="widthFix"> </image>
        <text class="logo-title">{{ $t('login.youWeiTongXun') }}</text>
      </view>
      <!-- 语言切换 -->
      <view class="lang flex item-center">
        <LanguageSwitch />
      </view>
    </view>
    <view class="page-bd">
      <view class="form">
        <view class="form-item">
          <input v-model="loginForm.username" type="text" class="input" :placeholder="$t('login.qingShuRuZhangHao')"
            maxlength="30" />
        </view>
        <view class="form-item">
          <InputPassword v-model="loginForm.password" />
        </view>
        <view class="form-info" v-if="errorMsg.length">{{ errorMsg }}</view>
        <view class="form-button">
          <button @click="handleLogin"
            :class="`btn login-btn cu-btn block bg-blue lg round ${loginAble ? 'btn-able' : ''}`">
            登录
            {{ $t('greeting') }}
          </button>
        </view>
      </view>

      <view class="agreement">

        <up-checkbox :customStyle="{ margin: '0px', fontSize: '24rpx', color: '#999' }" label="我已阅读并同意" name="agree"
          usedAlone v-model:checked="loginForm.agreement">
        </up-checkbox>
        <text @click="handleUserAgrement" class="text-blue">《服务条款》</text>
        <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
      </view>
    </view>
    <up-modal class="modal-agreement" :show="showAgreementModal" @cancel="showAgreementModal = false"
      @confirm="handleAgreement" confirmText="同意并登录" showCancelButton="true">
      <template>
        <view class="slot-content"> 我已阅读并同意<text>《服务条款》</text><text>《隐私政策》</text> </view>
      </template>
    </up-modal>
  </view>
</template>

<script setup>
import modal from '@/plugins/modal'
import { ref, reactive, computed, watch } from "vue";
import config from "@/config.js";
import useUserStore from '@/store/modules/user'
import LanguageSwitch from './components/language-switch/language-switch.vue';
import InputPassword from './components/input-password/input-password.vue';
// import AgreementModal from './components/agreement-modal/agreement-modal.vue';
import useLoginAgree from './hooks/loginAgree';
import { ROUTE } from '@/constant/constant';

const userStore = useUserStore()

const globalConfig = ref(config);
const errorMsg = ref("账号或密码错误，请重新输入");

// const loginForm = ref({
//   username: "admin",
//   password: "admin123",
//   cliendId: 'e5cd7e4891bf95d1d19206ce24a7b32e', // todo 全局参数
//   // agreement: false,
//   code: "",
//   uuid: ''
// });

const loginForm = ref({
  "username": "13012345678",
  "tenantId": "000001",
  "password": "123456",
  "agreement": false,
});

// 可登录状态
const loginAble = ref(false);
const showAgreementModal = ref(false);

// 协议弹窗确认事件 
function handleAgreement() {
  showAgreementModal.value = false;
  loginForm.value.agreement = true;
}

/**检测是否同意协议
 * @returns {boolean}
 */
function checkAgreement() {
  let result = true;
  if (!loginForm.value.agreement) {
    showAgreementModal.value = true;
    // uni.showModal({
    //   title: '提示',
    //   content: '你好',
    //   showCancel: false
    // })
    result = false;
  }

  return result;
}
// 点击登录按钮
async function handleLogin() {
  if (!loginAble) return;
  // 检测是否勾选
  if (!checkAgreement()) {
    return;
  }

  if (loginForm.value.username === "") {
    modal.msgError("请输入您的账号")
  } else if (loginForm.value.password === "") {
    modal.msgError("请输入您的密码")
  } else {
    modal.loading("登录中，请耐心等待...")
    pwdLogin()
  }
};

/**
 * 测试方法： 获取当前设置的语言
 */
function handleTest() {
  modal.alert('测试 getLocale:' + uni.getLocale())
}
// 密码登录
async function pwdLogin() {

  const { agreement, ...loginParams } = loginForm.value;
  userStore.actionLogin(loginParams).then(() => {
    modal.closeLoading()
    loginSuccess()
  }).catch(() => {
  })

};

function loginSuccess(result) {
  // 设置用户信息
  userStore.getInfo().then(res => {
    uni.switchTab({
      url: ROUTE.HOME
    });
  })
}

// 隐私协议
function handlePrivacy() {
  let site = globalConfig.value.appInfo.agreements[0];
  uni.navigateTo({
    url: `/pages/common/webview/index?title=${site.title}&url=${site.url}`
  });
};
// 用户协议
function handleUserAgrement() {
  let site = globalConfig.value.appInfo.agreements[1]
  uni.navigateTo({
    url: `/pages/common/webview/index?title=${site.title}&url=${site.url}`
  });
};

watch(() => [loginForm.value.username, loginForm.value.password], (arr) => {
  (arr[0]?.length && arr[1]?.length) ? loginAble.value = true : loginAble.value = false;
}, {
  immediate: true,
  deep: true
});

</script>

<style scoped lang="scss">
@import "@/static/scss/theme.scss";
$border-color: #E5E5EB;
$theme-color: #1951FA;
$error-color: #F53F3F;

.page {
  margin: 0 48px;

  &-hd {
    margin-top: 100px;
    justify-content: space-between;
    align-items: center;
    height: 70rpx;

    .logo {
      display: flex;
      align-items: center;

      &-img {
        width: 120rpx;
        height: 120rpx;
        margin-right: 20rpx;
        flex-shrink: 0;
        vertical-align: middle;
      }

      &-title {
        max-width: 220rpx;
        word-break: break-word;
        color: #1A1A1A;
        text-align: center;
        font-family: "Alimama ShuHeiTi";
        font-size: 40rpx;
        font-style: normal;
        font-weight: 700;
        line-height: 68rpx;
        /* 170% */
      }
    }

    .lang {
      flex-shrink: 0;
    }

  }

  &-bd {

    margin-top: 48px;
  }

  .form {
    &-item {
      padding: 32rpx 0;
      font-family: "PingFang SC";
      font-size: 30rpx;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
      border-bottom: 1px solid $border-color;
    }

    &-info {
      color: $error-color;
      font-family: "PingFang SC";
      font-size: 24rpx;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
      margin-top: 16rpx;
    }

    &-button {
      margin-top: 48px;

      .btn {
        line-height: 88rpx;
        font-size: 32rpx;
        border-radius: 8rpx;
        background-color: #D1DCFE;
        color: #fff;

        &-able {
          background-color: $theme-color;
        }
      }
    }


  }

  .agreement {
    display: flex;
    justify-content: center;
    margin-top: 48rpx;

    .text-blue {
      color: $theme-color;
      font-size: 24rpx;
    }
  }

  .color-theme {
    color: $theme-color;
  }
}
</style>
